<template>
    <div class="create">
        <p class="c_title">创建入库单</p>
        <div class="formArea">
            <el-form :model="createForm" :rules="rules" ref="createForm" label-width="80px" size="mini"
                :hide-required-asterisk="true">
                <el-form-item label="入库单号">
                    <el-input v-model="createForm.code" placeholder="请输入,忽略将自动生成"></el-input>
                </el-form-item>
                <el-form-item prop="typeOther">
                    <template slot='label'>
                        <span style="color: red">*</span>
                        入库类型
                    </template>
                    <el-select v-model="createForm.typeOther" filterable>
                        <el-option v-for="item in rklxOptions" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="time">
                    <template slot='label'>
                        <span style="color: red">*</span>
                        入库时间
                    </template>
                    <el-date-picker v-model="createForm.time" type="datetime">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" v-model="createForm.comment" :autosize="{ minRows:4}"></el-input>
                </el-form-item>
                <!-- ====================自定义==================== -->
                <el-form-item v-for='(item, i) in customFiledList' :key="i" :label='item.chineseName' :prop="item.id"
                    v-show='hiddenRule(item)'>
                    <el-checkbox-group v-show="false" v-model="createForm[item.id]"></el-checkbox-group>
                    <template slot='label'>
                        <span style="color: red" v-show="requireRsterisk(item)">*</span>
                        {{ item.chineseName }}
                        <el-tooltip class="item" effect="dark" :content="item.tips" placement="top" v-show='item.tips'>
                            <span class="iconfont icon-wenhao wenhao"></span>
                        </el-tooltip>
                    </template>
                    <formLibrary :formItem='item' @formItemHandle='formItemHandle' :defaultData="defaultData"
                        @uploadProgress='uploadProgress' ref='formLibrary'>
                    </formLibrary>
                </el-form-item>
            </el-form>
        </div>

        <div class="line">
            <span></span>
        </div>

        <!-- 入库明细 -->
        <instock-Detail @productTableList='productTableList' ref='detail'></instock-Detail>

        <div class="btn">
            <el-button type="primary" plain size="small" @click="$router.push('/stockManagement/inStock')">取消
            </el-button>
            <el-button type="primary" size="small" @click="handleProduct">保存</el-button>
        </div>
    </div>
</template>

<script>
    import {
        stockHandle,
        stockDetail
    } from '@/api/stockController'
    import {
        loginUserMess
    } from '@/api/loginController'
    import {
        customFieldOther,
        fillFieldMess,
    } from '@/api/customFieldController'
    import instockDetail from './instockDetail.vue'
    import formLibrary from '@/components/formLibrary'
    export default {
        data() {
            return {
                createForm: {
                    id:'',
                    code: '',
                    typeOther: '普通入库',
                    time: new Date(),
                    comment: '',
                    type: 0
                },
                rules: {
                    typeOther: [{
                        required: true,
                    }],
                    time: [{
                        required: true,
                        message: '入库时间不能为空！'
                    }],
                },
                rklxOptions: [{
                    value: '普通入库',
                    label: '普通入库'
                }, {
                    value: '采购入库',
                    label: '采购入库'
                }, {
                    value: '成品入库',
                    label: '成品入库'
                }, {
                    value: '调拨入库',
                    label: '调拨入库'
                }, {
                    value: '销售退货入库',
                    label: '销售退货入库'
                }, {
                    value: '其它入库',
                    label: '其它入库'
                }],
                list:[],
                customFiledList: [],
                defaultData: [], // 自定义字段值
                customFiledData: [],
                customState: true, // 判断单选/复选 选值是否正确
                customErrorLabel: '', // 选值错误提示语
                // 关联属性信息
                relevanceProp: [],
                userMess: {},
                uploadFlag: true,
            }
        },
        components: {
            formLibrary,
            instockDetail
        },
        watch: {
            createForm: {
                handler() {
                    this.hiddenRule('')
                },
                deep: true,
            }
        },
        mounted() {
            this.getStockDetail({
                id: this.$route.query.id,
                type: 0
            })
        },
        methods: {
            // 自定义字段
            getCustomFieldOther() {
                customFieldOther({
                    type: 'stock'
                }).then(res => {
                    this.customFiledList = []
                    this.relevanceProp = []
                    if (res.code == 200) {
                        // 自定义字段数据
                        res.data.map(item => {
                            item.customFieldMess.objectsValue = item.objectsValue
                            this.customFiledList.push(item.customFieldMess)
                        })
                        // 添加自定义字段的校验规则(是否必填)
                        this.customFiledList.map(item => {
                            let r = item.hidden
                            item.hidden = r.replace(/\${出入库单./g, 'formItemData["').replace(/\}/g, '"]')
                                .replace(/\${用户信息./g, 'userFormItemData["')
                            item.id = item.id + ''
                            let obj = {}
                            if (JSON.parse(item.fieldAttribute).required && item.fieldType != 'inputNumber') {
                                obj[item.id] = [{
                                    required: true,
                                    message: item.chineseName + '不能为空'
                                }]
                            }else if(item.fieldType == 'inputNumber'){
                                const numberRule = (rule, v, callback) => {
                                    let tempValue = ''
                                    let index = String(this.createForm[item.id]).indexOf('.')
                                    tempValue = index != -1 ? String(this.createForm[item.id]).slice(0,index) : String(this.createForm[item.id])
                                    if (!this.createForm[item.id] && item.isRequired) {
                                        return callback(new Error(`${item.chineseName}不能为空！`));
                                    }else if(tempValue.length > 10){
                                        return callback(new Error('整数位最多支持10位数字'));
                                    }else if(this.createForm[item.id] != undefined && !(/^[0-9]+(.[0-9]{1,6})?$/.test(this.createForm[item.id]))){
                                        return callback(new Error('小数点后最多保留6位数字'));
                                    }else {
                                        callback()
                                    }
                                }
                                obj[item.id] = [{
                                    validator: numberRule,
                                    trigger:'blur'
                                }]
                            }
                            this.rules = Object.assign(this.rules, obj)
                            if (item.fieldType == 'relevanceProp') {
                                this.relevanceProp.push({
                                    id: item.id,
                                    objectFieldId: item.objectFieldId,
                                    type: item.correlationField
                                })
                            }
                        })
                        this.getLoginUserMess()
                    }
                })
            },
            // 用户信息
            getLoginUserMess(data) {
                loginUserMess(data).then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        this.userMess = res.data
                    }
                })
            },
            // 关联对象-字段信息
            getFillFieldMess(data, fillRule, n) {
                fillFieldMess(data).then(res => {
                    this.defaultData = []
                    for (let key in this.createForm) {
                        if (Number(key)) {
                            this.defaultData.push({
                                customFieldId: key,
                                value: this.createForm[key]
                            })
                        }
                    }
                    if (res.code == 200) {
                        // 如果该条数据有自定义字段
                        if (res.data.customFieldVos != null) {
                            /* 
                                遍历关联对象的填充规则
                                遍历该条数据的自定义字段列表
                                将填充规则中的来源值(from) 赋给 指定控件(to)
                            */
                            fillRule.map(item => {
                                let dataArr = []
                                let f = res.data.customFieldVos.find(res => {
                                    return res.customFieldId == item.from
                                })
                                if (f != undefined) {
                                    res.data.customFieldVos.map(k => {
                                        if (k.customFieldId == item.from) {
                                            this.createForm[item.to] = k.value
                                            this.defaultData = this.defaultData.filter(j => j
                                                .customFieldId != item.to)
                                            this.defaultData.push({
                                                customFieldId: item.to,
                                                value: k.value
                                            })
                                        }
                                    })
                                } else {
                                    this.createForm[item.to] = ''
                                    this.defaultData.map(k => {
                                        if (k.customFieldId == item.to) {
                                            let d = this.customFiledList.find(res => {
                                                return res.id == item.to
                                            })
                                            if (d.fieldType == 'picture' || d.fieldType ==
                                                'upload' || d.fieldType == 'selectChecked') {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: "[]"
                                                })
                                            } else {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: ""
                                                })
                                            }
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: k.value
                                            })
                                        }
                                    })
                                    this.defaultData = dataArr
                                }
                            })
                        } else {
                            fillRule.map(item => {
                                let dataArr = []
                                this.createForm[item.to] = ''
                                this.defaultData.map(k => {
                                    if (k.customFieldId == item.to) {
                                        let d = this.customFiledList.find(res => {
                                            return res.id == item.to
                                        })
                                        if (d.fieldType == 'picture' || d.fieldType ==
                                            'upload' || d.fieldType == 'selectChecked') {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: "[]"
                                            })
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: ""
                                            })
                                        }
                                    } else {
                                        dataArr.push({
                                            customFieldId: k.customFieldId,
                                            value: k.value
                                        })
                                    }
                                })
                                this.defaultData = dataArr
                            })
                        }
                        // 关联属性赋值
                        this.relevanceProp.map(item => {
                            if (item.objectFieldId == n) {
                                this.createForm[item.id] = res.data[item.type]
                                this.defaultData = this.defaultData.filter(j => j.customFieldId != item
                                    .id)
                                this.defaultData.push({
                                    customFieldId: item.id,
                                    value: res.data[item.type]
                                })
                            }
                        })
                    }
                })
            },
            // 自定义表单项数据--表单子组件传递的值
            formItemHandle(d) {
                // 子组件的值赋给表单
                this.$set(this.createForm, d.name, d.value)
                // 操作的是关联对象
                if (d.relevanceObject != undefined) {
                    if (d.relevanceObject.id) {
                        let data = {
                            id: d.relevanceObject.id,
                            type: d.relevanceObject.businessObject
                        }
                        this.getFillFieldMess(data, d.relevanceObject.fillRule, d.name)
                    } else {
                        this.customFiledList.map(item => {
                            if (item.objectFieldId == d.name) {
                                this.createForm[item.id] = ''
                                this.defaultData.map(k => {
                                    if (k.customFieldId == item.id || k.customFieldId == d.name) {
                                        k.value = ''
                                    }
                                })
                            }
                        })
                        for (let key in this.createForm) {
                            let ind = this.defaultData.findIndex(res => {
                                return res.customFieldId == key
                            })
                            if (ind != -1) {
                                this.$set(this.defaultData, ind, {
                                    customFieldId: key,
                                    value: this.createForm[key]
                                })
                            } else {
                                this.defaultData.push({
                                    customFieldId: key,
                                    value: this.createForm[key]
                                })
                            }
                        }
                    }
                }
            },
            // 自定义隐藏设置--隐藏条件触发
            hiddenRule(d) {
                let formItemData = {
                    '入库单号': this.createForm.code,
                    '入库类型': this.createForm.typeOther,
                    '入库时间': this.utils.formatTime(this.createForm.time, 'yyyy-MM-dd hh:mm:ss'),
                    '备注': this.createForm.comment
                }
                let userFormItemData = {
                    '账号': this.userMess.account,
                    '姓名': this.userMess.name,
                    '手机号': this.userMess.mobile,
                    '角色': this.userMess.role,
                }
                this.customFiledList.map(item => {
                    if (formItemData[item.chineseName] == undefined) {
                        if (this.createForm[item.id] != undefined) {
                            formItemData[item.chineseName] = this.createForm[item.id]
                        } else {
                            formItemData[item.chineseName] = ''
                        }
                    }
                    if (userFormItemData[item.chineseName] == undefined) {
                        if (this.createForm[item.id] != undefined) {
                            userFormItemData[item.chineseName] = this.createForm[item.id]
                        } else {
                            userFormItemData[item.chineseName] = ''
                        }
                    }
                })
                let state = null
                try {
                    state = !eval(d.hidden)
                } catch {
                    state = true
                }
                //必填项字段若是被隐藏不校验
                if (this.rules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        if(JSON.parse(d.fieldAttribute).required){ //inputNumber 必填 && 切换触发隐藏条件
                            d.isRequired = state
                        }
                    }else{
                        this.rules[d.id][0].required = state
                    }
                }
                return state
            },
            requireRsterisk(d) {
                if (this.rules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        return JSON.parse(d.fieldAttribute).required || false
                    }else{
                        return this.rules[d.id][0].required || false
                    }
                }
            },
            customData(v, data) {
                if (Number(v)) {
                    let id = ''
                    data.map(item => {
                        if (item.value == v) {
                            id = item.label
                        }
                    })
                    return id
                } else {
                    return v
                }
            },
            // 附件/图片上传是否完成
            uploadProgress(s) {
                this.uploadFlag = s
            },

            //详情
            getStockDetail(data) {
                stockDetail(data).then(res => {
                    if (res.code == 200) {
                        this.createForm.id = this.$route.query.id
                        this.createForm.code = res.data.code
                        this.createForm.typeOther = res.data.typeOther
                        this.createForm.time = res.data.time
                        this.createForm.comment = res.data.comment
                        this.customFiledData = []
                        this.defaultData = []
                        this.getCustomFieldOther()
                        // 不为null说明该条数据有自定义字段，将自定义字段值初始化给表单
                        if (res.data.customFieldVos != null) {
                            res.data.customFieldVos.map(item => {
                                this.$set(this.createForm, item.customFieldId, item.value)
                                this.customFiledData.push({
                                    customFieldId: item.customFieldId,
                                    value: item.value
                                })
                                this.defaultData.push({
                                    customFieldId: item.customFieldId,
                                    value: item.value
                                })
                            })
                        }
                        //走导入数据的逻辑
                        this.$refs.detail.getProductTable({
                            title:'导入',
                            from:'fromEdit',
                            productTable:res.data.productList
                        })
                    }
                })
            },

            //入库单操作
            getStockHandle(data) {
                stockHandle(data).then(res => {
                    if (res.code == 200) {
                        this.$router.push('/stockManagement/inStock')
                        this.utils.showMsg('入库单编辑成功', 'success')
                    }
                })
            },

            //明细列表数据
            productTableList(list){
                this.list = list
            },
            handleCustomField(customFieldVos){
                let data = []
                data = customFieldVos === null ? [] : 
                    customFieldVos.map(k => {
                        return {
                            customFieldId:k.customFieldId,
                            value:k.value
                        }
                    })
                return data
            },
            //保存
            handleProduct() {
                this.$refs.createForm.validate((valid) => {
                    if (valid) {
                       if (!this.list.length) {
                            this.utils.showMsg('入库明细至少填写一项', 'warning')
                            return
                        }
                        let data = {}
                        let stockDetails = []
                        let customData = []
                        this.list.forEach(i => {
                            stockDetails.push({
                                productId:i.productId,
                                handleNum:i.handleNum,
                                customFieldVos:this.handleCustomField(i.customFieldVos) 
                            })
                        })
                        for (const key in this.createForm) {
                            if(!Number(key)){
                                data[key] = key == 'time' ? 
                                    this.utils.formatTime(this.createForm[key], 'yyyy-MM-dd hh:mm:ss') : this.createForm[key]
                            }else{
                                this.customFiledList.find(item => {
                                    if (item.id == key && this.createForm[key] != null &&
                                            String(this.createForm[key]).length) {
                                        customData.push({
                                            customFieldId: item.id,
                                            value: this.createForm[key]
                                        })
                                    }
                                })
                            }
                        }
                        // 关联对象后，判断单选框/复选框关联过来的值是否存在
                        this.customState = true
                        this.customErrorLabel = ''
                        this.customFiledList.map(item => {
                            // 单选框
                            if (item.fieldType == 'selectRadio') {
                                if (this.createForm[item.id] != '' && this.createForm[item.id] !=
                                    undefined) {
                                    let s = JSON.parse(item.checkBox).find(res => {
                                        return this.createForm[item.id] == res.value
                                    })
                                    if (s == undefined) {
                                        this.customState = false
                                        this.customErrorLabel = '【' + item.chineseName + '】选项值不正确'
                                    }
                                }
                            }
                            // 复选框
                            if (item.fieldType == 'selectChecked') {
                                if (this.createForm[item.id] != '' && this.createForm[item.id] !=
                                    undefined && this.createForm[item.id] != '[]') {
                                    JSON.parse(this.createForm[item.id]).map(k => {
                                        let s = JSON.parse(item.checkBox).find(res => {
                                            return res.value == k
                                        })
                                        if (s == undefined) {
                                            this.customState = false
                                            this.customErrorLabel = '【' + item.chineseName +
                                                '】选项值不正确'
                                        }
                                    })
                                }
                            }
                        })
                        data.customFieldVos = customData
                        data.stockDetails = stockDetails
                        if (this.customState) {
                            if (this.uploadFlag) {
                                this.$refs.formLibrary != undefined && this.$refs.formLibrary.map(k => {
                                    k.removeData('ok')
                                })
                                this.getStockHandle(data)
                            } else {
                                this.utils.showMsg('正在上传，请稍后', 'warning')
                            }
                        } else {
                            this.utils.showMsg(this.customErrorLabel, 'error')
                        }
                    } else {
                        return false;
                    }
                })
            },
        },
    }
</script>

<style lang="less" scoped>
    .create {
        overflow: auto;

        .c_title {
            padding: 20px 0 0 20px;
        }

        .formArea {
            width: 420px;
            padding: 20px 0px 0px 40px;
        }

        .line {
            padding: 0 20px;
            height: 1px;

            span {
                display: inline-block;
                width: 100%;
                height: 100%;
                border: 1px solid rgba(0, 0, 0, .06);
            }
        }

        .btn {
            margin: 26px 0;
            text-align: center;

            /deep/ .el-button--primary span {
                margin-left: 0;
            }

            /deep/ .el-button {
                padding: 7px 35px;
            }
        }

        /deep/ .el-dialog__body {
            padding: 10px 40px;
        }

        /deep/ .el-select {
            width: 100%;
        }

        /deep/ .el-input-number--mini {
            width: 100%;
        }

        /deep/ .el-date-editor.el-input {
            width: 100%;
        }

        /deep/ .el-range-editor.el-input__inner {
            width: 100%;
        }
    }
</style>